package com.macro.mall.tiny.modules.ums.controller;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.common.api.ResultCode;
import com.macro.mall.tiny.common.service.RedisService;
import com.macro.mall.tiny.component.wx.WxClient;
import com.macro.mall.tiny.component.wx.entity.bo.WxBO;
import com.macro.mall.tiny.modules.oms.model.OmsGood;
import com.macro.mall.tiny.modules.oms.service.OmsOrderService;
import com.macro.mall.tiny.modules.oms.service.impl.OmsGoodServiceImpl;
import com.macro.mall.tiny.modules.ums.model.UmsMember;
import com.macro.mall.tiny.modules.ums.service.UmsMemberService;
import com.macro.mall.tiny.modules.ums.vo.LoginVO;
import com.macro.mall.tiny.security.util.MemberContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 小程序用户表 前端控制器
 * </p>
 *
 * @author tyrone
 * @since 2024-10-14
 */
@RestController
@RequestMapping("/ums/umsMember")
@Api(tags = "UmsMemberController")
@Tag(name = "UmsMemberController", description = "前台用户管理")
public class UmsMemberController {
    @Autowired
    private UmsMemberService umsMemberService;


    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private UmsMemberService memberService;

    @Autowired
    private WxClient wxClient;
    @Autowired
    private OmsGoodServiceImpl omsGoodServiceImpl;

    @Autowired
    private RedisService redisService;

    @Scheduled(cron = "0 5 * * * ?")
    public void checkVipStatus(){
        umsMemberService.list(new QueryWrapper<UmsMember>().isNotNull("vip_expire_time").lt("vip_expire_time", new Date())).forEach(umsMember -> {
            umsMember.setVip(0);
            umsMember.setVipExpireTime(null);
            umsMemberService.updateById(umsMember);
        });
    }


    @ApiOperation("用户注册绑定手机号，只有在真正绑定了手机号才算是注册成功")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<UmsMember> register(@ApiParam("小程序用户openId") @RequestParam String openId, @ApiParam("手机号获取凭证") @RequestParam String code) {
        UmsMember um = memberService.getUmsMemberByOpenId(openId);
        if (um != null && !ObjectUtils.isEmpty(um.getPhone())) {
            return CommonResult.success(null, "用户已绑定手机号");
        }
        if (um == null) {
            memberService.register(openId);
            um = memberService.getUmsMemberByOpenId(openId);
        }
        if (ObjectUtils.isEmpty(um.getPhone())) {
            WxBO wxBO = wxClient.getUserPhone(code);
            if (wxBO.getSuccess()) {
                um.setPhone(wxBO.getPurePhone());
                um.setStatus(1);
                umsMemberService.updateById(um);
                return CommonResult.success(um, "绑定成功");
            }
        }
        return CommonResult.failed("绑定失败");

    }


    @ApiOperation(value = "用户信息填充", notes = "userId和openId必须要有一个")
    @RequestMapping(value = "/fillInfo", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult fillInfo(@RequestBody UmsMember umsMember) {
        UmsMember member = MemberContext.getMember();
        if (member == null) {
            return CommonResult.failed(ResultCode.FORBIDDEN);
        }
        umsMember.setId(member.getId());
        return memberService.fillInfo(umsMember);
    }

    @ApiOperation("用户登录")
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<LoginVO> login(@RequestParam String jsCode) {
        CommonResult<LoginVO> check = memberService.check(jsCode);
        LoginVO data = (LoginVO) check.getData();
        data.setTokenHead("Bearer ");
        return check;
    }

    @ApiOperation("获取用户信息")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult info(@RequestParam Long memberId) {
        UmsMember um = MemberContext.getMember();
        if (um == null || !um.getId().equals(memberId)) {
            return CommonResult.failed(ResultCode.FORBIDDEN);
        }
        UmsMember member = memberService.getUmsMemberById(memberId);
        return CommonResult.success(member);
    }

//    @ApiOperation("获取验证码")
//    @RequestMapping(value = "/getAuthCode", method = RequestMethod.GET)
//    @ResponseBody
//    public CommonResult getAuthCode(@RequestParam String telephone,@RequestParam String openId) {
//        String authCode = memberService.generateauthcode(telephone,openId);
//        return CommonResult.success(authCode, "获取验证码成功");
//    }

    @ApiOperation(value = "刷新token")
    @RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = memberService.refreshToken(token);
        if (refreshToken == null) {
            return CommonResult.failed("token已经过期！");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation("后台分页获取")
    @PostMapping("page")
    public CommonResult<IPage<UmsMember>> page(@RequestBody UmsMemberDTO dto) {
        QueryWrapper<UmsMember> query = new QueryWrapper<>();
        if (dto.getId() != null) {
            query.eq("id", dto.getId());
        }

        if (StringUtils.isNotEmpty(dto.getOpenId())) {
            query.eq("open_id", dto.getOpenId());
        }
        if (StringUtils.isNotEmpty(dto.getPhone())) {
            query.eq("phone", dto.getPhone());
        }
        if (StringUtils.isNotEmpty(dto.getNickname())) {
            query.like("nick_name", dto.getNickname());
        }
        if (dto.getStatus() != null) {
            query.eq("status", dto.getStatus());
        }
        if (dto.getVip() != null) {
            query.eq("vip", dto.getVip());
        }
        if (dto.getCreateTimeStart() != null) {
            query.ge("create_time", dto.getCreateTimeStart());
        }
        if (dto.getCreateTimeEnd() != null) {
            query.le("create_time", dto.getCreateTimeEnd());
        }
        if (dto.getVipExpireTimeStart() != null) {
            query.ge("vip_expire_time", dto.getVipExpireTimeStart());
        }
        if (dto.getVipExpireTimeEnd() != null) {
            query.le("vip_expire_time", dto.getVipExpireTimeEnd());
        }
        query.orderByDesc("create_time");
        IPage<UmsMember> result = umsMemberService.page(new Page<>(dto.getPageNum(), dto.getPageSize(), Boolean.TRUE), query);

        return CommonResult.success(result);

    }

    @ApiOperation("用户转发app添加7天会员")
    @PostMapping("forward")
    public CommonResult<Void> forward(@RequestBody UmsMemberDTO dto) {
        UmsMember member = MemberContext.getMember();
        if (member == null) {
            return CommonResult.failed(ResultCode.UNAUTHORIZED);
        }
        Object exist = redisService.get("vip_forward:" + member.getId());
        if (exist != null) {
            return CommonResult.failed("已经领取过了");
        }
        UmsMember umsMember = umsMemberService.getById(member.getId());
        umsMember.setVip(1);
        umsMember.setVipExpireTime(DateUtil.offsetDay(umsMember.getVipExpireTime() == null ? new Date() : umsMember.getVipExpireTime(), 7).toJdkDate());
        umsMemberService.updateById(umsMember);
        redisService.set("forward:" + member.getId(), new Date().getTime());
        return CommonResult.success(null);
    }

    @ApiOperation("后台批量修改用户vip权限")
    @PostMapping("batchVip")
    public CommonResult<Void> batchVip(@RequestBody UmsMemberVIPDTO dto) {

        if (dto.getMemberIds() == null || dto.getMemberIds().isEmpty()) {
            return CommonResult.failed(ResultCode.VALIDATE_FAILED);
        }

        // 关闭会员
        if (dto.getVipStatus() != null && dto.getVipStatus() == 0) {
            dto.getMemberIds().forEach(memberId -> {
                UmsMember umsMember = umsMemberService.getById(memberId);
                umsMember.setVip(0);
                umsMember.setVipExpireTime(null);
                umsMemberService.updateById(umsMember);
            });
        }
        if (dto.getVipStatus() != null && dto.getVipStatus() == 1) {
            // 开启会员
            Integer vipPlanId = dto.getVipPlanId();
            OmsGood good = omsGoodServiceImpl.getById(vipPlanId);
            dto.getMemberIds().forEach(memberId -> {
                UmsMember umsMember = umsMemberService.getById(memberId);
                umsMember.setVip(1);
                umsMember.setVipExpireTime(DateUtil.offsetDay(new Date(), good.getDuration()).toJdkDate());
                umsMemberService.updateById(umsMember);
            });
        }

        if (dto.getBalance() != null) {
            dto.getMemberIds().forEach(memberId -> {
                UmsMember umsMember = umsMemberService.getById(memberId);
                umsMember.setBalance(dto.getBalance());
                umsMemberService.updateById(umsMember);
            });
        }


        return CommonResult.success(null);

    }

    @Data
    public static class UmsMemberVIPDTO {
        @ApiModelProperty("用户ids")
        private List<Long> memberIds;

        @ApiModelProperty("vip套餐id 如果是关闭的话 可以不传")
        private Integer vipPlanId;

        @ApiModelProperty("0关闭 1开启")
        private Integer vipStatus;

        private Integer balance;
    }

    @Data
    public static class UmsMemberDTO {
        @ApiModelProperty(value = "用户id")
        private Long id;
        @ApiModelProperty(value = "用户openId")
        private String openId;

        @ApiModelProperty(value = "用户手机号")
        private String phone;

        @ApiModelProperty(value = "用户昵称")
        private String nickname;

        @ApiModelProperty(value = "用户状态")
        private Integer status;

        @ApiModelProperty(value = "用户vip")
        private Integer vip;

        @ApiModelProperty("创建时间起")
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date createTimeStart;

        @ApiModelProperty("创建时间止")
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date createTimeEnd;

        @ApiModelProperty("vip过期时间起")
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date vipExpireTimeStart;

        @ApiModelProperty("vip过期时间止")
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date vipExpireTimeEnd;

        @ApiModelProperty("分页参数")
        private Integer pageSize;

        @ApiModelProperty("分页参数")
        private Integer pageNum;
    }


}

